//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using LitwareHR.PublicApp.Presenters.Careers;
using LitwareHR.Recruiting.Contract;
using Shp.Runtime.Contract;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using LitwareHR.PublicApp.WebUX.Properties;

public partial class Careers_SearchResumes : BasePage, ISearchResumesView
{
	public SearchResumesPresenter Presenter { get; private set; }

	public string Address
	{
		get { return AddressTextBox.Text; }
	}

	public DateTime DateFrom
	{
		get { return ParseDateTime(FromTextBox.Text, DateTime.MinValue); }
	}

	public DateTime DateTo
	{
		get { return ParseDateTime(ToTextBox.Text, DateTime.MaxValue); }
	}

	public bool CrossTenant
	{
		get { return CrossTenantCheckBox.Checked; }
	}

	public void HideCrossTenantResults()
	{
		CrossTenantPanel.Visible = false;
	}

	public void ShowLocalTenantResumeResult(Resume[] resumes)
	{
		ResumeResultGridView.DataSource = resumes;
		ResumeResultGridView.DataBind();
	}

	public void ShowCrossTenantResumeResult(Resume[] resumes)
	{
		CrossTenantPanel.Visible = true;
		CrossTenantResumeResultGridView.DataSource = resumes;
		CrossTenantResumeResultGridView.DataBind();
	}

	public void ShowCustomFilters(Collection<PropertyFilter> customFilters)
	{
		Session["customFilters"] = customFilters;
		CustomFiltersGridView.DataSource = customFilters;
		CustomFiltersGridView.DataBind();
	}

	public void SetCustomFields(IEnumerable<EntityField> customFields)
	{
		bool visiblePanelCustomFields = false;
		Session["customFields"] = customFields;
		if (customFields != null)
		{
			foreach (EntityField entity in customFields)
			{
				visiblePanelCustomFields = true;
				CustomFieldsDropDownList.Items.Add(entity.Name);
				
				BoundField boundField = new BoundField();
				boundField.HeaderText = entity.Name;

				ResumeResultGridView.Columns.Add(boundField);
			}
		}
		CustomFieldsPanel.Visible = visiblePanelCustomFields;
	}

    public void SetDetailsLink(string resumeDetailsLink)
    {
        HyperLinkField detailsLink = ResumeResultGridView.Columns[0] as HyperLinkField;
        detailsLink.DataNavigateUrlFormatString = resumeDetailsLink;
    }

	protected override void OnInitComplete(EventArgs e)
	{
		base.OnInitComplete(e);
		Presenter = new SearchResumesPresenter(this);
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		if (IsPostBack)
		{
			Presenter.CustomFields = (IEnumerable<EntityField>)Session["customFields"];
			Presenter.CustomFilters = (Collection<PropertyFilter>)Session["customFilters"];
		}
		else
		{
			Session["customFields"] = null;
			Session["customFilters"] = null;
			Presenter.OnViewLoaded(Helpers.TenantAlias);
		}
	}

	protected void SearchButton_Click(object sender, EventArgs e)
	{
		Presenter.OnSearch();
	}

	protected void ClearButton_Click(object sender, EventArgs e)
	{
		this.AddressTextBox.Text = string.Empty;
		this.FromTextBox.Text = string.Empty;
		this.ToTextBox.Text = string.Empty;
		Presenter.ClearCustomFilters();
	}

	protected void AddButton_Click(object sender, EventArgs e)
	{
		if (ConnectorsList.Text == "And")
		{
			Presenter.AddCustomFilter(CustomFieldsDropDownList.Text, CustomValueTextBox.Text, LogicalConnector.And);
		}
		else
		{
			if (ConnectorsList.Text == "Or")
			{
				Presenter.AddCustomFilter(CustomFieldsDropDownList.Text, CustomValueTextBox.Text, LogicalConnector.Or);
			}
		}
	}

	private static DateTime ParseDateTime(string dateString, DateTime unparseableValue)
	{
		DateTime parsed;
		if (!DateTime.TryParse(dateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out parsed))
		{
			parsed = unparseableValue;
		}

		return parsed;
	}

	protected void ResumeResultGridView_RowDataBound(object sender, GridViewRowEventArgs e)
	{		
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				IEnumerable<EntityField> customFields = (IEnumerable<EntityField>)Session["customFields"];
				
				for (int i = 0; i < ResumeResultGridView.Columns.Count; i++)
				{
                    string columnHeaderText=ResumeResultGridView.Columns[i].HeaderText;
                    if (customFields.Count(cust => cust.Name == columnHeaderText) > 0 )
					{
						Resume niceResume = e.Row.DataItem as Resume;
                        if (niceResume.Fields.Count(f => f.Name == columnHeaderText) > 0)
                        {
                            e.Row.Cells[i].Text = niceResume.Fields.Single(f => f.Name == columnHeaderText).Value;
                        }
					}
				}
			}
	}

    protected void CrossTenantResumeResultGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView customFields = e.Row.FindControl("ResumeDetailsGridView") as GridView;
            Resume resume = e.Row.DataItem as Resume;
            if (customFields != null && resume!=null)
            {
                customFields.DataSource = resume.Fields;
                customFields.DataBind();
            }
        }
    }
}

